package com.ruoyi.web.controller.game;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.constant.NumConstants;
import com.ruoyi.system.domain.bo.YanzhengmaBo;
import com.ruoyi.web.core.config.XzsConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SgXmYanzhengma;
import com.ruoyi.system.service.ISgXmYanzhengmaService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @since 2024-10-20
 */
@Api(value = "熊猫验证码处理类")
@RestController
@RequestMapping("/yanzhengma")
@Slf4j
public class SgXmYanzhengmaController extends BaseController
{
    @Autowired
    private ISgXmYanzhengmaService sgXmYanzhengmaService;

    @Resource
    private XzsConfig xzsConfig;

    @ApiOperation("添加验证码")
    @PostMapping("/add")
    public AjaxResult addYZM(@RequestBody  @Valid YanzhengmaBo bo)
    {
        return toAjax(sgXmYanzhengmaService.addYZM(bo));
    }

    @ApiOperation("获得验证码坐标")
    @PostMapping("/zb")
    public AjaxResult getYZMZB(@RequestBody YanzhengmaBo bo)
    {
        String yzmzb;
        String imgUrl=bo.getImgurl();
        if(StringUtils.isEmpty(imgUrl)){
            return AjaxResult.error("图片地址为空");
        }
        log.info("验证码坐标获取开始 | YanzhengmaBo:{}", JSONObject.toJSONString(bo));
        yzmzb = sgXmYanzhengmaService.getYZMZB(bo);
        if(yzmzb == null || yzmzb.isEmpty()) {
            try {
                log.info("验证码坐标获取开始 | YanzhengmaBo:{}", JSONObject.toJSONString(bo));
                //传入的是keywords和url
                String keywords = bo.getKeyworks().trim();
                if (StringUtils.isNotEmpty(keywords) && keywords.length() == NumConstants.TWO) {
                    //将keywords的两个字中间加入逗号分割,如飞萌分割为飞,萌
                    keywords = keywords.charAt(NumConstants.ZERO) + "," + keywords.charAt(NumConstants.ONE);
                    //post 请求url地址获得json字符串将json字符串转为json对象
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("image_url", bo.getImgurl());
                    jsonObject.put("characters_to_find", keywords);
                    String url = xzsConfig.getRecognizeService();
                    String result = HttpUtils.sendPostJson(url, jsonObject.toString());
                    log.info("AI识别结果：{}", result);
                    if (!result.equals("[]")) {
                /*
                * 返回json体
                *  [
                      {
                        "character": "阵",
                        "center_x": 237,
                        "center_y": 120
                      },
                      {
                        "character": "为",
                        "center_x": 164,
                        "center_y": 47
                      }
                    ]
                * */
                        JSONArray list = JSONArray.parseArray(result);
                        String[] keywordsArr = keywords.split(",");
                        StringBuilder sb = new StringBuilder();
                        for (String c : keywordsArr) {
                            //使用流 遍历json数组，找到对应的字符，将坐标放入数组中
                            list.stream()
                                    .filter(item -> item instanceof JSONObject)
                                    .map(item -> (JSONObject) item)
                                    .filter(item -> item.getString("character").equals(c))
                                    .forEach(item -> {
                                        //将坐标放入数组中
                                        sb.append(item.get("center_x").toString()).append(",").append(item.get("center_y").toString());
                                        if (sb.length() > NumConstants.ZERO) {
                                            sb.append(",");
                                        }
                                    });

                        }
                        if (sb.length() > NumConstants.ZERO) {
                            yzmzb = sb.toString();
                            yzmzb = yzmzb.substring(0, yzmzb.lastIndexOf(","));
                        }


                    }
                }
            } catch (Exception e) {
                log.error("验证码坐标获取失败 | 关键词:{} | 图片URL:{} | 异常信息:{}",
                        bo.getKeyworks(),
                        bo.getImgurl(),
                        e.getMessage(),
                        e);
            }
        }
        log.info("验证码{}({}):坐标获取结束：{}",bo.getKeyworks(),imgUrl,yzmzb);
        if(StringUtils.isBlank(yzmzb)){
            return error("验证码坐标获取失败");
        }else{
            return AjaxResult.success("获取成功",yzmzb);
        }

    }
    /**
     * 更新验证码
     */
    @ApiOperation("更新验证码")
    @PostMapping("update")
    public AjaxResult XMYZMUpdateToImg(@RequestBody  @Valid YanzhengmaBo bo)
    {
        return toAjax(sgXmYanzhengmaService.updateToImg(bo));
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:list')")
    @GetMapping("/list")
    public TableDataInfo list(SgXmYanzhengma sgXmYanzhengma)
    {
        startPage();
        List<SgXmYanzhengma> list = sgXmYanzhengmaService.selectSgXmYanzhengmaList(sgXmYanzhengma);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SgXmYanzhengma sgXmYanzhengma)
    {
        List<SgXmYanzhengma> list = sgXmYanzhengmaService.selectSgXmYanzhengmaList(sgXmYanzhengma);
        //ExcelUtil<SgXmYanzhengma> util = new ExcelUtil<SgXmYanzhengma>(SgXmYanzhengma.class);
        ExcelUtil<SgXmYanzhengma> util = new ExcelUtil<>(SgXmYanzhengma.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sgXmYanzhengmaService.selectSgXmYanzhengmaById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SgXmYanzhengma sgXmYanzhengma)
    {
        return toAjax(sgXmYanzhengmaService.insertSgXmYanzhengma(sgXmYanzhengma));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SgXmYanzhengma sgXmYanzhengma)
    {
        return toAjax(sgXmYanzhengmaService.updateSgXmYanzhengma(sgXmYanzhengma));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:yanzhengma:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sgXmYanzhengmaService.deleteSgXmYanzhengmaByIds(ids));
    }
}
